package com.fengmi.exception;

import cn.hutool.json.JSONUtil;
import com.fengmi.vo.InfoResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author: 施俊豪
 * Date: 2022/2/7 11:25
 * Note: 自定义403异常处理
 */
@Component
public class MyAccessDenied implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //设置响应状态码
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        //设置响应数据格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //输入响应内容
        PrintWriter writer = null;
        try {
            writer = httpServletResponse.getWriter();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        InfoResult infoResult = new InfoResult(false, "没有权限访问","");
        infoResult.setBcCode("403");
        writer.write(JSONUtil.toJsonPrettyStr(infoResult));
        writer.flush();
    }
}
